<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\command\report;

use app\command\BaseWork;
use app\enum\ReportRecordEnum;
use app\model\ReportRecordPushModel;
use app\service\report\ReportPullService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class ReportRecordPushConsumerWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('report_record_push_consumer_work');
        $this->setDescription('实时发送报表消费者');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('拉取实时报表数据开始');
        $st = time() + (5 * 60);
        $redis = Cache::store('redis')->handler();
        $key = ReportRecordEnum::CONFIG_KEY['report_pull_fetch'];
        while (time() < $st) {
            $pullId = intval($redis->lPop($key));
            if (! $pullId) {
                usleep(500000);
                continue;
            }
            try {
                $this->getOutputMessage('拉取实时报表数据开始,报表id:' . $pullId);
                ReportPullService::setStatus($pullId, ReportRecordPushModel::STATUS_WAIT_SYNC);
                if (! ReportPullService::getReportRecordContent($pullId)) {
                    throw new \Exception(ReportPullService::getError(0));
                }
                ReportPullService::setStatus($pullId, ReportRecordPushModel::STATUS_SYNC);
                $this->getOutputMessage('拉取实时报表数据成功,报表id:' . $pullId);
                $redis->rPush(ReportRecordEnum::CONFIG_KEY['report_process_fetch'], $pullId);
            } catch (\Exception $e) {
                ReportPullService::setStatus($pullId, ReportRecordPushModel::STATUS_NO);
                $this->getOutputMessage('拉取实时报表数据失败,报表id:' . $e->getMessage());
            }
        }
        $this->getOutputMessage('拉取实时报表数据结束');
    }
}
